package cn.emall.cart.interceptor;

import cn.emall.pojo.TbUser;
import cn.emall.sso.service.TokenService;
import cn.emall.utils.CookieUtils;
import cn.emall.utils.EmallResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录处理拦截器
 */
public class LoginInterceptor implements HandlerInterceptor{

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //前处理,执行handler前执行此方法
        //返回true为方形,false为拦截
        //1.从cookie中获取token
        String token = CookieUtils.getCookieValue(request, "token");
        //2.如果没有token,用户没有登录,放行
        if(StringUtils.isBlank(token)){
            return true;
        }
        //3.取到token,调用sso服务根据token获取用户信息
        EmallResult result = tokenService.getUserByToken(token);
        //4.没有取到用户信息,登录过期,直接放行
        if(result.getStatus() != 200){
            return true;
        }
        //5.取到登录信息,登录状态
        TbUser user = (TbUser) result.getData();
        //6.把用户信息放到request中.只需要在CartController中判断是否包含有user信息,放行
        request.setAttribute("user",user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        //handler执行之后，返回ModeAndView之前
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        //完成处理，返回ModelAndView之后。
        //可以再此处理异常
    }
}
